package com.i2works.smartluolong.web.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.i2works.smartluolong.utils.base.AppConstant;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.basecommon.BaseCommonServiceImpl;
import com.i2works.smartluolong.utils.common.BaseUtils;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.DAOException;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.dal.user.dao.IUserAccountDAO;
import com.i2works.smartluolong.web.entity.common.SelectDO;
import com.i2works.smartluolong.web.entity.user.*;
import com.i2works.smartluolong.web.service.common.UserPasswordHelper;
import com.i2works.smartluolong.web.service.user.IUserAccountExtendService;
import com.i2works.smartluolong.web.service.user.IUserAccountService;
import com.xiaoleilu.hutool.collection.CollUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 会员账号表实现类
 *
 * @author Liu Yutao koal@vip.qq.com
 * @date 2016/1/26 14:30ServiceImpl implements
 */
@Service("userAccountService")
public class UserAccountServiceImpl extends BaseCommonServiceImpl<UserAccountQuery, UserAccountDO> implements IUserAccountService {

    private final IUserAccountDAO userAccountDAO;

    private final UserPasswordHelper userPasswordHelper;

    private final IUserAccountExtendService userAccountExtendService;

    @Autowired
    public UserAccountServiceImpl(IUserAccountDAO userAccountDAO, UserPasswordHelper userPasswordHelper, IUserAccountExtendService userAccountExtendService) {
        this.userAccountDAO = userAccountDAO;
        this.userPasswordHelper = userPasswordHelper;
        this.userAccountExtendService = userAccountExtendService;
    }


    /**
     * 内部添加用户角色方法
     */
    private void saveUserRole(UserAccountDO userAccountDO) throws ServiceException {
        try {
            //获取角色数组
            String[] roleSelect = userAccountDO.getRoleSelect();
            if (ArrayUtils.isNotEmpty(roleSelect)) {
                List<String> roleList = Arrays.asList(roleSelect);
                if (CollUtil.isNotEmpty(roleList)) {
                    //添加已选角色
                    for (String roleId : roleList) {
                        UserAccountRoleDO userRole = new UserAccountRoleDO();
                        userRole.setAccountId(userAccountDO.getId());
                        userRole.setRoleId(Integer.parseInt(roleId));
                        userAccountDAO.saveUserRole(userRole);
                    }
                }
            }

        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 添加编辑普通会员
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void save(UserAccountDO userAccountDO) throws ServiceException {
        try {
            if (userAccountDO.getId() != null && userAccountDO.getId() != 0) {
                //更新用户
                userAccountDAO.update(userAccountDO);
                //删除用户所有角色
                userAccountDAO.deleteUserRole(userAccountDO.getId());
                //添加用户角色
                saveUserRole(userAccountDO);
            } else {
                //新增用户
                userPasswordHelper.encryptPassword(userAccountDO);
                userAccountDO.setCreateName(userAccountDO.getUpdateName());
                int count = userAccountDAO.save(userAccountDO);
                if (count > 0) {
                    //添加用户角色
                    saveUserRole(userAccountDO);
                }
            }

        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }


    /**
     * APP用户登录查询
     */
    @Override
    public Result queryAppLoginUser(UserLoginVO userLogin) throws ServiceException {
        try {
            //查询用户提交的账号信息
            UserAccountQuery accountQuery = new UserAccountQuery();
            accountQuery.setUserName(userLogin.getUserName());
            Integer userCount = userAccountDAO.queryCheck(accountQuery);
            if (userCount > 0) {
                UserAccountDO userAccount = userAccountDAO.queryLoginUser(userLogin.getUserName());
                UserAccountExtendQuery query = new UserAccountExtendQuery();
                query.setUserId(userAccount.getId());
                UserAccountExtendDO userAccountExtend = userAccountExtendService.query(query);
                userAccount.setAvatar(userAccountExtend.getAvatar());
                userAccount.setRealName(userAccountExtend.getRealName());
                String password = userAccount.getPassword();
                String encryptPassword = userPasswordHelper.encryptPassword(userLogin.getPassword(), userAccount.getSalt());
                if (password.equalsIgnoreCase(encryptPassword)) {
                    UserAccountVO userAccountVO = new UserAccountVO();
                    BeanUtils.copyProperties(userAccount, userAccountVO);
                    return R.success(MsgEnum.ACCESS_LOGIN_SUCCESS.getMsg(), userAccountVO);
                } else {
                    return R.error(MsgEnum.ACCESS_ERROR.getMsg());
                }
            } else {
                return R.error(MsgEnum.ACCESS_UNKNOW.getMsg());
            }
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }


    /**
     * 注册用户
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public Integer saveRegisterUser(UserAccountDO userAccountDO) throws ServiceException {
        Integer regStatus;
        try {
            //新增用户
            userPasswordHelper.encryptPassword(userAccountDO);
            userAccountDO.setStatus(GlobalConstant.status.TRUE);
            regStatus = userAccountDAO.save(userAccountDO);
            if (regStatus > 0) {
                //添加角色
                //保存用户和角色资源表
                UserAccountRoleDO accountRoleDO = new UserAccountRoleDO();
                accountRoleDO.setAccountId(userAccountDO.getId());
                accountRoleDO.setRoleId(GlobalConstant.USER_ROLE_NUMBER);
                userAccountDAO.saveUserRole(accountRoleDO);
              /*  //保存用户扩展信息
                UserAccountExtendDO userAccountExtendDO = new UserAccountExtendDO();
                userAccountExtendDO.setUserId(userAccountDO.getId());
                userAccountExtendDO.setAvatar(AppConstant.UPLOAD_IMAGE_AVATAR);
                userAccountExtendDO.setStatus(GlobalConstant.status.TRUE);
                userAccountExtendDO.setUpdateName(userAccountDO.getUserName());
                userAccountExtendDO.setCreateName(userAccountDO.getUserName());
                userAccountExtendService.save(userAccountExtendDO);
*/            }
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
        return regStatus;
    }


    /**
     * 修改密码
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void updatePassword(UserAccountDO userAccountDO) throws ServiceException {
        try {
            userPasswordHelper.encryptPassword(userAccountDO);
            userAccountDAO.updatePassword(userAccountDO);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 批量修改密码
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void updateBatchPassword(Map map) throws ServiceException {
        try {
            if (map != null && map.size() > 0) {
                List<UserAccountDO> userAccountList = JSON.parseArray(String.valueOf(map.get("userAccountList")), UserAccountDO.class);
                String updateName = String.valueOf(map.get("updateName"));
                for (UserAccountDO userAccountDO : userAccountList) {
                    userAccountDO.setUpdateName(updateName);
                    userAccountDO.setPassword(GlobalConstant.DEFAULT_PASSWORD);
                    userPasswordHelper.encryptPassword(userAccountDO);
                    userAccountDAO.update(userAccountDO);
                }
            }
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 查询一个普通用户（登陆）
     */
    @Override
    public UserAccountDO queryLoginUser(String value) throws ServiceException {
        try {
            return userAccountDAO.queryLoginUser(value);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 查询某会员的角色列表
     */
    @Override
    public List<SelectDO> queryRoleSelect(Integer userId) throws ServiceException {
        try {
            return userAccountDAO.queryRoleSelect(userId);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 查询用户详细列表
     */
    @Override
    public List<UserAccountVO> queryUserDetailsList(UserAccountQuery query) throws ServiceException {
        try {
            List<UserAccountDO> doList = userAccountDAO.queryUserDetailsList(query);
            List<UserAccountVO> voList = Lists.newArrayList();
            if (CollectionUtil.isNotEmpty(doList)) {
                voList = BaseUtils.do2voList(doList, UserAccountVO.class);
            }
            return voList;
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }


    /**
     * 查询用户详细列表总量
     */
    @Override
    public Integer queryUserDetailsCount(UserAccountQuery query) throws ServiceException {
        try {
            return userAccountDAO.queryUserDetailsCount(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 查询用户详情（后台列表接口）
     */
    @Override
    public List<UserAccountVO> queryUserInfoApiList(UserAccountQuery query) throws ServiceException {

        try {
            List<UserAccountDO> doList = userAccountDAO.queryUserInfoApiList(query);
            List<UserAccountVO> voList = Lists.newArrayList();
            return BaseUtils.do2voList(doList, UserAccountVO.class);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 查询用户详情统计（后台列表接口）
     */
    @Override
    public Integer queryUserInfoApiCount(UserAccountQuery query) throws ServiceException {
        try {
            return userAccountDAO.queryUserInfoApiCount(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }


    /**
     * 删除会员
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void delete(Integer id) throws ServiceException {
        try {
            userAccountDAO.delete(id);
            userAccountDAO.deleteUserRole(id);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 批量删除会员
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public void deleteBatch(List<Integer> idsList) throws ServiceException {
        try {
            userAccountDAO.deleteBatch(idsList);
            userAccountDAO.deleteBatchUserRole(idsList);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }


	@Override
	public void updateByPhone(UserAccountDO userAccountDO) throws ServiceException {
		try {
			userAccountDAO.updateByPhone(userAccountDO);
		} catch (DAOException e) {
			throw new ServiceException(e);
		}
		
	}

}
